package com.seeyoui.kensite.framework.system.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.cxf.transport.http.Cookies;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.google.common.collect.Lists;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.CacheUtils;
import com.seeyoui.kensite.common.util.CookieUtils;
import com.seeyoui.kensite.common.util.MD5;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.framework.plugin.skins.domain.Skins;
import com.seeyoui.kensite.framework.plugin.skins.service.SkinsService;
import com.seeyoui.kensite.framework.system.domain.SysUser;
import com.seeyoui.kensite.framework.system.domain.SysUserDto;
import com.seeyoui.kensite.framework.system.service.SysUserService;
import com.seeyoui.kensite.framework.system.util.SkinsUtils;
import com.seeyoui.kensite.framework.system.util.UserUtils;

/**
 * 程序名称： LoginController.java.java
 * 程序说明：登录controller
 * @version： Ver 0.1
 */

@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {
	
	@Autowired
	private SkinsService skinsService;
	@Autowired
	private SysUserService sysUserService;
	
	/**
	 * 账号登录
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/userLogin", method=RequestMethod.POST)
	public String loginIn(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap,String loginType) {
		String info = "";
		Boolean status = true;
		String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		password = MD5.md5(userName + password);
		
		/// sessionId
        /*String sid = session.getId();
        System.out.println("------------"+sid+"--------");
        System.out.println("测试session");
        Cookie[] cs = request.getCookies();
        for (Cookie cookie : cs) {
        	System.out.println(cookie.getValue());
		}
        String infoString = request.getHeader("cookie");
        System.out.println("=================="+infoString);*/
        
//        //获取HttpSession中的验证码
//        String verifyCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        //获取用户请求表单中输入的验证码
//        String submitCode = request.getParameter("verifyCode");
//        System.out.println("用户[" + userName + "]登录时输入的验证码为[" + submitCode + "],HttpSession中的验证码为[" + verifyCode + "]");
//        if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){
//        	info = "验证码不正确";
//        	modelMap.put("info", info);
//        	return resultPageURL;
//        }
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		token.setRememberMe(true);
		// 获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
		} catch (UnknownAccountException uae) {
			info = "未知账户";
			status = false;
		} catch (IncorrectCredentialsException ice) {
			info = "密码不正确";
			status = false;
			// 冻结账户相关方法
			blockedUser(userName);
		} catch (LockedAccountException lae) {
			info = "账户已锁定,请联系管理员";
			status = false;
		} catch (ExcessiveAttemptsException eae) {
			info = "用户名或密码错误次数过多";
			status = false;
		} catch (AuthenticationException ae) {
			ae.printStackTrace();
			info = "账户状态异常";
			status = false;
		}
		
		// 采购端登录，验证用户是否与公司有关联
		
		
		
		// 验证是否登录成功
		if (currentUser.isAuthenticated() && status) {
			// 成功
			Object loginObject = CacheUtils.get("loginFail");
			if(loginObject != null){
				@SuppressWarnings("unchecked")
				Map<String, List<Date>> loginFailMap = (Map<String, List<Date>>) loginObject;
				loginFailMap.remove(userName);
			}
			String theme = CookieUtils.getCookie(request, "current-theme");
			modelMap.put("theme", "skin-" + theme);
			if("".equals(loginType) || loginType == null){
				resultPageURL = "redirect:/cms/article/articleList?categoryId=9a076290eab144238ba33765a35fe7f8";
			}else if("distributor".equals(loginType)){
				resultPageURL = "";
			}else if("customer".equals(loginType)){
				resultPageURL = "";
			}
		} else {
			// 失败
			token.clear();
			UserUtils.clearCache();
			SecurityUtils.getSubject().logout();
			modelMap.put("info", info);
		}

		return resultPageURL;
	}
	
	/**
	 * APP登录接口
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/loginApp", method=RequestMethod.POST)
	@ResponseBody
	public Result loginApp(String username, String password,
			HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		@SuppressWarnings("unused")
		String info = "";
		Boolean status = true;
		password = MD5.md5(username + password);

		/*
		 * String sid = session.getId();
		 * System.out.println("------------"+sid+"--------");
		 * System.out.println("测试session");
		 */

		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
		} catch (UnknownAccountException uae) {
			info = "未知账户";
			status = false;
		} catch (IncorrectCredentialsException ice) {
			info = "密码不正确";
			status = false;
			// 冻结账户相关方法
			blockedUser(username);
		} catch (LockedAccountException lae) {
			info = "账户已锁定";
			status = false;
		} catch (ExcessiveAttemptsException eae) {
			info = "用户名或密码错误次数过多";
			status = false;
		} catch (AuthenticationException ae) {
			ae.printStackTrace();
			info = "账户状态异常";
			status = false;
		}
		if (currentUser.isAuthenticated() && status) {
			Object loginObject = CacheUtils.get("loginFail");
			if(loginObject != null){
				Map<String, List<Date>> loginFailMap = (Map<String, List<Date>>) loginObject;
				loginFailMap.remove(username);
			}
			SysUser loginUser = sysUserService.findByUserName(username);
			SysUserDto userDto = new SysUserDto(loginUser.getId(),
					loginUser.getName(), loginUser.getHeadIcon());
			System.out.println("成功");
			return Result.success(userDto);
		}
		// 登录失败
		System.out.println("失败");
		return Result.failure(info);
	}
	
	/**
	 * 进入后台管理页面
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/toManage")
	public String gotoManage(HttpServletRequest request, ModelMap modelMap) {
		String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
		String theme = CookieUtils.getCookie(request, "current-theme");
		modelMap.put("theme", "skin-" + theme);
		resultPageURL = getSysSkins();
		return resultPageURL;
	}
	
	/**
	 * 账号登出
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public String loginOut(HttpSession session, ModelMap modelMap) {
		UserUtils.clearCache();
		SecurityUtils.getSubject().logout();  
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/";
	}
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}
	
	/**
	 * 获取系统皮肤方案
	 */
	public String getSysSkins() {
    	Skins skin = SkinsUtils.getCurSysSkins();
    	if(skin==null || skin.getUrl()==null || "".equals(skin.getUrl())) {
    		return "skins/poor/main";
    	} else {
    		return "skins"+skin.getUrl()+"/"+skin.getMain();
    	}
	}
	
	/**
	 * 密码输入错误大于三次，冻结账户
	 * @param userName
	 */
	public void blockedUser(String userName) {
		Object loginObject = CacheUtils.get("loginFail");
		if (null == loginObject) {
			Map<String, List<Date>> loginFailMap = new HashMap<String, List<Date>>();
			loginFailMap.put(userName, Lists.newArrayList(new Date()));
			CacheUtils.put("loginFail", loginFailMap);
		} else {
			@SuppressWarnings("unchecked")
			Map<String, List<Date>> loginFailMap = (Map<String, List<Date>>) loginObject;
			List<Date> list = loginFailMap.get(userName);
			if (null == list) {
				loginFailMap.put(userName, Lists.newArrayList(new Date()));
			} else {
				// 该用户的登录失败记录不为空
				list.add(new Date());
				int failCountInOneHour = 0;
				for (Date date : list) {
					if ((System.currentTimeMillis() - date.getTime()) < 1000 * 60 * 60) {
						failCountInOneHour++;
						if (failCountInOneHour >= 4) {
							// 冻结账户
							SysUser sysUser = sysUserService
									.findByUserName(userName);
							sysUser.setState("0");
							sysUserService.updateState(sysUser);
							// 清除缓存
							loginFailMap.remove(userName);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 登陆首页主区域页面
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/skinsPage/{url}")
	public String mainContent(@PathVariable("url") String url, HttpSession session, ModelMap modelMap) {
		return "skins/"+url;
	}
	
	/**
	 * 登陆首页主区域页面
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/skinsPage/common/{url}")
	public String commonPage(@PathVariable("url") String url, HttpSession session, ModelMap modelMap) {
		return "skins/common/"+url;
	}
	
}

